package com.dy.yunying.biz.service.manage.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.yunying.api.entity.AdRoleGame;
import com.dy.yunying.api.entity.AdRoleUser;
import com.dy.yunying.api.entity.WanGameDO;
import com.dy.yunying.api.feign.RemoteAdRoleUserService;
import com.dy.yunying.api.req.AdRoleUserReq;
import com.dy.yunying.biz.config.YunYingProperties;
import com.dy.yunying.biz.dao.manage.AdRoleGameMapper;
import com.dy.yunying.biz.dao.manage.AdRoleUserMapper;
import com.dy.yunying.biz.dao.manage.ext.GameDOMapperExt;
import com.dy.yunying.biz.service.manage.AdRoleUserService;
import com.google.common.collect.Lists;
import com.pig4cloud.pig.admin.api.entity.SysUser;
import com.pig4cloud.pig.admin.api.feign.RemoteUserService;
import com.pig4cloud.pig.admin.api.vo.UserSelectVO;
import com.pig4cloud.pig.api.entity.AdAccount;
import com.pig4cloud.pig.api.feign.RemoteAccountService;
import com.pig4cloud.pig.api.vo.AdAccountVo;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.constant.enums.AdRoleGameTypeEnum;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 角色可查看的平台用户
 *
 * @author zhuxm
 * @date 2021-06-04
 */
@Service
@RequiredArgsConstructor
public class AdRoleUserServiceImpl extends ServiceImpl<AdRoleUserMapper, AdRoleUser> implements AdRoleUserService {

	private final AdRoleUserMapper adRoleUserMapper;

	private final AdRoleGameMapper adRoleGameMapper;

	private final GameDOMapperExt gameDOMapperExt;

	private final RemoteUserService remoteUserService;

	private final RemoteAccountService remoteAccountService;

	private final RemoteAdRoleUserService remoteAdRoleUserService;

	private final YunYingProperties yunYingProperties;

	/**
	 * @return
	 */
	@Override
	public List<Integer> getOwnerRoleUserIds() {
		List<Integer> userIdList = new ArrayList<>();
		List<UserSelectVO> users = this.getOwnerRoleUsers4All();
		if (CollectionUtil.isNotEmpty(users)) {
			for (UserSelectVO userSelectVO: users) {
				userIdList.add(userSelectVO.getUserId());
			}
		}
		return userIdList;
	}


	/**
	 * 含删除的用户
	 * @return
	 */
	public List<UserSelectVO> getOwnerRoleUsers4All(){
		List<UserSelectVO> resultList = new ArrayList<>();
		R r  = remoteUserService.getUserSelectList4All();
		if(r.getCode() == CommonConstants.SUCCESS){
			//所有用户列表
			resultList = (List<UserSelectVO>) r.getData();
		}
		return this.setUserList(resultList==null?new ArrayList<>():resultList);
	}


	/**
	 * 不含删除的用户
	 * @return
	 */
	@Override
	public List<UserSelectVO> getOwnerRoleUsers(){
		List<UserSelectVO> resultList = new ArrayList<>();
		R r  = remoteUserService.getUserSelectList();
		if(r.getCode() == CommonConstants.SUCCESS){
			//所有用户列表
			resultList = (List<UserSelectVO>) r.getData();
		}
		return this.setUserList(resultList==null?new ArrayList<>():resultList);
	}

	private List<UserSelectVO> setUserList(List<UserSelectVO> resultList) {
		//将自身加入
		Integer userId = SecurityUtils.getUser().getId();
		List<UserSelectVO> ownerList =  resultList.stream().filter(item -> item.getUserId().equals(userId)).collect(Collectors.toList());

		//当前角色包含的平台账号


		List<Integer> roles = SecurityUtils.getRoles();
		if(roles != null && roles.size() > 0){
			List<AdRoleUser> list = adRoleUserMapper.selectList(Wrappers.<AdRoleUser>query().lambda().in(AdRoleUser :: getRoleId,  roles));
			Set<Integer> roleuserList = list.stream().map(AdRoleUser::getUserId).collect(Collectors.toSet());
			//ad_role_user表中维护数据
			if(roleuserList != null && roleuserList.size() > 0){
				if(!roleuserList.contains(0)){
					roleuserList.add(userId);
					return resultList.stream().filter(item -> roleuserList.contains(item.getUserId())).collect(Collectors.toList());
				}else{

				}
				//ad_role_user表没有数据
			}else{
				//增加自身
				return ownerList;
			}
			//当前用户没有角色
		}else{
			//增加自身
			return ownerList;
		}
		return resultList;
	}

	/**
	 * 当前登录人所关联角色对应的投放人集合
	 * @return
	 */
	@Override
	public List<Integer> getThrowUserList() {
		//投放人集合
		List<Integer> throwUserList = Lists.newArrayList();
		//获取当前登入人所有的角色
		List<Integer> roles = SecurityUtils.getRoles();
		Integer userId = SecurityUtils.getUser().getId();
		//角色没有设置投放人，需要计算当前人是否关联了广告账户
		throwUserList.add(userId);
		//管理员获取当前所有的账户
		if (!roles.contains(1)) {
			//非管理员
			//1.获取当前账户对应的角色 roles
			//2.获取角色关联的投放人-关联全部则与管理员权限一致
			R<List<AdRoleUser>> adRoleUserList = remoteAdRoleUserService.getUserListByRole(SecurityConstants.FROM_IN,roles);
			if (CollectionUtils.isNotEmpty(adRoleUserList.getData())) {
				List<Integer> userIds = adRoleUserList.getData().stream().distinct().map(AdRoleUser::getUserId).collect(Collectors.toList());
				//存在关联了全部投放人的角色则与管理员权限一致
				//userId = 0 表示关联全部
				if (!userIds.contains(0)) {
					List<Integer> userIdStr = userIds.stream().distinct().collect(Collectors.toList());
					throwUserList.addAll(userIdStr);
				} else {
					throwUserList.clear();
				}
			} else {
				throwUserList.add(-1);
			}
		} else {
			throwUserList.clear();
		}
		return throwUserList;
	}

	/**
	 * 当前登录人所关联角色对应的投放人的广告账户集合
	 * @return
	 */
	@Override
	public List<String> getThrowAccountList() {
		List<String> accountList = Lists.newArrayList();
		List<Integer> throwUserList = this.getThrowUserList();
		if (CollectionUtils.isNotEmpty(throwUserList)) {
			accountList = remoteAccountService.getAccountList2(throwUserList, SecurityConstants.FROM_IN);
			if (CollectionUtils.isEmpty(accountList)){
				accountList.add("-1");
			}
		}
		return accountList;
	}

	/**
	 * 	获取自身权限下的子游戏列表
	 * @param
	 * @return
	 */
	@Override
	public List<Integer> getThrowRoleGames(){
		List<Integer> resultList = com.google.api.client.util.Lists.newArrayList();
		//自身角色
		List<Integer> roles = SecurityUtils.getRoles();
		if(roles != null && roles.size() > 0) {
			//含有的角色对应的游戏
			List<AdRoleGame> list = adRoleGameMapper.selectList(Wrappers.<AdRoleGame>query().lambda().in(AdRoleGame::getRoleId, roles));
			if(CollectionUtils.isNotEmpty(list)){
				Set<WanGameDO> gameList = new HashSet<>();
				Set<Integer> typeList = list.stream().map(AdRoleGame::getType).collect(Collectors.toSet());
				//含有全部游戏，子查询所有全部游戏
				if(typeList.contains(AdRoleGameTypeEnum.All.getValue())){
					return resultList;
				}
				if(typeList.contains(AdRoleGameTypeEnum.PGID.getValue())){
					List<Long> pgids = list.stream().filter(v -> v.getType().equals(AdRoleGameTypeEnum.PGID.getValue())).map(AdRoleGame::getGameid).collect(Collectors.toList());
					//查询主游戏id的子游戏列表
					List<WanGameDO> gameDbList =  gameDOMapperExt.selectList(Wrappers.<WanGameDO>query()
							.lambda().in(WanGameDO::getPgid, pgids)
							.orderByAsc(WanGameDO::getId));
					gameList.addAll(gameDbList);
				}
				if(typeList.contains(AdRoleGameTypeEnum.GAMEID.getValue())){
					List<Long> gameids = list.stream().filter(v -> v.getType().equals(AdRoleGameTypeEnum.GAMEID.getValue())).map(AdRoleGame::getGameid).collect(Collectors.toList());
					//查询子游戏列表
					List<WanGameDO> gameDbList =  gameDOMapperExt.selectList(Wrappers.<WanGameDO>query()
							.lambda().in(WanGameDO::getId, gameids)
							.orderByAsc(WanGameDO::getId));
					gameList.addAll(gameDbList);
				}
				resultList = gameList.stream().map(v -> v.getId().intValue()).collect(Collectors.toList());
				resultList.add(-1);
				return resultList;
			} else {
				resultList.add(-1);
			}
		} else {
			resultList.add(-1);
		}
		return resultList;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveRoleUser(AdRoleUserReq adRoleUserReq){
		adRoleUserMapper.delete(Wrappers.<AdRoleUser>query().lambda().eq(AdRoleUser::getRoleId, adRoleUserReq.getRoleId()));
		if (StringUtils.isNotEmpty(adRoleUserReq.getUserIds())) {
			String[] users = adRoleUserReq.getUserIds().split(",");
			for(String userid : users ){
				AdRoleUser adRoleUser = new AdRoleUser();
				adRoleUser.setRoleId(adRoleUserReq.getRoleId());
				adRoleUser.setUserId(Integer.parseInt(userid));
				adRoleUserMapper.insert(adRoleUser);
			}
		}
	}

	/**
	 * 投放人绑定广告账户并且激活的的用户
	 * @return
	 */
	@Override
	public R bindingUserList(){
		R<List<SysUser>> result  = remoteUserService.getUserList(SecurityConstants.FROM_IN);
		if(result.getCode() == CommonConstants.SUCCESS && CollectionUtils.isNotEmpty(result.getData())){
			List<AdAccount> accountList = remoteAccountService.getAllList(new AdAccountVo(), SecurityConstants.FROM_IN);
			if (CollectionUtils.isNotEmpty(accountList)){
				List<String> accountListFilter = accountList.stream().map(AdAccount::getThrowUser).distinct().filter(item -> StringUtils.isNotBlank(item)).collect(Collectors.toList());
				if (CollectionUtils.isNotEmpty(accountListFilter)){
					List<SysUser> userSelectVOList = result.getData();
					List<UserSelectVO> userListFilterActivation = userSelectVOList.stream()
							.filter(v -> Objects.nonNull(v.getStatus()) && 1 == v.getStatus().intValue() && accountListFilter.contains(String.valueOf(v.getUserId())))
							.map(item -> {return new UserSelectVO().setUserId(item.getUserId()).setUsername(item.getUsername()).setRealName(item.getRealName()).setStatus(item.getStatus());})
							.collect(Collectors.toList());
					return R.ok(userListFilterActivation);
				}
			}
		}
		return R.ok();
	}
	/**
	 * 投放人已激活的用户
	 * @return
	 */
	@Override
	public R activationUserList(){
		R<List<SysUser>> result  = remoteUserService.getUserList(SecurityConstants.FROM_IN);
		if(result.getCode() == CommonConstants.SUCCESS && CollectionUtils.isNotEmpty(result.getData())){
			List<SysUser> userSelectVOList = result.getData();
			List<UserSelectVO> userListFilterActivation = userSelectVOList.stream()
					.filter(v -> Objects.nonNull(v.getStatus()) && 1 == v.getStatus().intValue())
					.map(item -> {return new UserSelectVO().setUserId(item.getUserId()).setUsername(item.getUsername()).setRealName(item.getRealName()).setStatus(item.getStatus());})
					.collect(Collectors.toList());
			return R.ok(userListFilterActivation);
		}
		return R.ok();
	}

	@Override
	public R selectCpsUserList() {
		return remoteUserService.getUserSelectListByTenantId(SecurityConstants.FROM_IN,yunYingProperties.getTenantId());
	}


	/**
	 * 查询飞书用户信息
	 * @return
	 */
	@Override
	public R selectFsUserList() {
		return remoteUserService.getUserSelectListByTenantId(SecurityConstants.FROM_IN,yunYingProperties.getTenantId());
	}

}
